//
//  FriendDetailViewController.m
//  Guazi
//
//  Created by koolearn on 11-8-4.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "FriendDetailViewController.h"
#import "ImageStore.h"
#import "GuaziAppDelegate.h"
#import "NetworkUtil.h"
#import "CardDetailViewController.h"
#import "ContactGroupViewController.h"
#import "UserTimelineController.h"
#import "FriendListViewController.h"
#import "UserService.h"


#define kActionSheetFollow 102
#define kActionSheetRequestCard 103


@interface FriendDetailViewController (private)
- (void) setOperationButtonStyle:(UIButton*)button;
- (void) setInfoButtonStyle:(UIButton*)button;
- (void) setButtonEnabled;
- (void) setDeleteButtonTitle;

- (void) loadUserProfile;
- (UIImage*) getProfileImage:(NSString*)url isLarge:(BOOL)flag;

- (void) send:(NSArray*)recipients body:(NSString*)body;
- (void) displaySMSComposerSheet:(NSArray*)recipients body:(NSString*)body;
- (void) createFriendship;
- (void) destroyFriendship;
- (void) askCard;
@end

@implementation FriendDetailViewController


@synthesize phoneButton;
@synthesize smsButton;
@synthesize cardButton;
@synthesize groupButton;
@synthesize editButton;
@synthesize deleteButton;
@synthesize friendButton;
@synthesize timelineButton;
@synthesize user;
@synthesize userView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id) initWithUser:(User*)auser
{
    self = [super init];
    if ( self ) {
        self.user = auser;
    }
    return self;
}


- (void)dealloc
{
    [smsButton release];
    [cardButton release];
    [groupButton release];
    [editButton release];
    [deleteButton release];
    [friendButton release];
    [timelineButton release];
    [phoneButton release];
    [user release];
    [userView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    owner = ([GuaziAppDelegate getAppDelegate].user.userId == user.userId);
    
    [self setOperationButtonStyle:phoneButton];
    [self setOperationButtonStyle:smsButton];
    [self setOperationButtonStyle:cardButton];
    [self setOperationButtonStyle:groupButton];
    [self setOperationButtonStyle:editButton];
    [self setOperationButtonStyle:deleteButton];

    [self setInfoButtonStyle:friendButton];
    [self setInfoButtonStyle:timelineButton];
    
    self.userView.linkToProfileView = NO;
    self.userView.frame = CGRectMake(0, 0, 320, 70);
    [self.userView updateUser:user];
    [self.userView setNeedsLayout];
    [self.userView setNeedsDisplay];
 
    [self setButtonEnabled];
    [self loadUserProfile];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    self.smsButton = nil;
    self.cardButton = nil;
    self.groupButton = nil;
    self.editButton = nil;
    self.deleteButton = nil;
    self.friendButton = nil;
    self.timelineButton = nil;
    self.phoneButton = nil;
    self.user = nil;
    self.userView = nil;
}


- (void) viewWillDisappear:(BOOL)animated
{
    if ( twitterClient ) {
        [twitterClient cancel];
        [twitterClient release];
        twitterClient = nil;
    }
    [super viewWillDisappear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void) setButtonEnabled
{
    //名片
    if ( [user.state compare:kUserStateValid] == NSOrderedSame ) {
        self.cardButton.enabled = YES;
    }
    else {
        self.cardButton.enabled = NO;
    }
    
    //私信
    //if ( [user.state compare:kUserStateValid] == NSOrderedSame && [user.relation compare:kUserRelationBoth] == NSOrderedSame ) 
    //    return YES;
    //else return NO;

    //电话
    if ( !owner && user.phone && [user.phone length] > 0 ) {
        self.phoneButton.enabled = YES;
    }
    else {
        self.phoneButton.enabled = NO;
    }

    //sms
    if ( !owner && user.phone && [user.phone length] > 0 ) {
        self.smsButton.enabled = YES;
    }
    else {
        self.smsButton.enabled = NO;
    }
    
    //group
    if ( owner ) {
        self.groupButton.enabled = NO;
    }
    else {
        self.groupButton.enabled = YES;
    }
    
    //edit
    if ( owner ) {
        self.editButton.enabled = NO;
    }
    else {
        self.editButton.enabled = YES;
    }
    
    //delete
    if ( owner ) {
        self.deleteButton.enabled = NO;
    }
    else {
        self.deleteButton.enabled = YES;
    }
    
    //分享的好友
    if ( [user.state compare:kUserStateValid] == NSOrderedSame && user.friendsCount > 0 ) {
        self.friendButton.enabled = YES;
    }
    else {
        self.friendButton.enabled = NO;
    }
    
    //分享的动态
    if ( [user.state compare:kUserStateValid] == NSOrderedSame && user.statusesCount > 0 ) {
        self.timelineButton.enabled = YES;
    }
    else {
        self.timelineButton.enabled = NO;
    }
}


#pragma mark - load data methods

- (void) loadUserProfile
{
    if ( [kUserStateValid compare:user.state] != NSOrderedSame ) return;
    
    if ( [NetworkUtil isbroadbandAvailable] ) {
        if ( twitterClient ) return;
        twitterClient = [[TwitterClient alloc] initWithTarget:self action:@selector(userDidReceive:obj:)];
        [twitterClient getUserById:user.userId];
    }
    else {
        NSArray* cards = (NSMutableArray*) [Card cardsForUser:user.userId];
        user.cards = cards;
    }
}

- (void)userDidReceive:(TwitterClient*)sender obj:(NSObject*)obj
{
    twitterClient = nil;    
    
    if (sender.hasError) {
        [sender alert];
        return;
    }
    
    if ( obj == nil || obj == [NSNull null] ) return;
    if ( ![obj isKindOfClass:[NSDictionary class]] ) return;
    
    NSDictionary *dic = (NSDictionary*) obj;
    [user updateWithJSonDictionary:dic];
    [user updateDB:YES withName:NO withAccount:NO];
    [Card setCardsForUser:user.userId cards:user.cards];
    
    [friendButton setTitle:[NSString stringWithFormat:@"分享的联系人(%d)", user.friendsCount] forState:UIControlStateNormal];
    [timelineButton setTitle:[NSString stringWithFormat:@"分享的动态(%d)", user.statusesCount] forState:UIControlStateNormal];
    friendButton.titleLabel.textColor = [UIColor colorWithRed:0.41f green:0.41f blue:0.41f alpha:1.0f];
    timelineButton.titleLabel.textColor = [UIColor colorWithRed:0.41f green:0.41f blue:0.41f alpha:1.0f];

    [self setButtonEnabled];
}



#pragma mark - tool methods

- (void) setOperationButtonStyle:(UIButton*)button
{
    button.layer.masksToBounds=YES;
    button.layer.cornerRadius=7.0;
    button.layer.borderWidth=1.0;
    button.layer.borderColor = [UIColor colorWithRed:0.75f green:0.75f blue:0.75f alpha:1.0f].CGColor;
    [button setBackgroundColor:[UIColor whiteColor]];
    //button.titleLabel.textColor = [UIColor colorWithRed:0.41f green:0.41f blue:0.41f alpha:1.0f];
}


- (void) setInfoButtonStyle:(UIButton*)button
{
    button.layer.masksToBounds=YES;
    button.layer.cornerRadius=7.0;
    button.layer.borderWidth=1.0;
    button.layer.borderColor = [UIColor colorWithRed:0.75f green:0.75f blue:0.75f alpha:1.0f].CGColor;
    [button setBackgroundColor:[UIColor colorWithRed:1.0f green:1.0f blue:0.75f alpha:1.0f]];
    //button.titleLabel.textColor = [UIColor colorWithRed:0.41f green:0.41f blue:0.41f alpha:1.0f];
}


- (void) setDeleteButtonTitle
{
    if ( owner ) return;
    
    if ( [user.relation compare:kUserRelationFollowing]==NSOrderedSame || [user.relation compare:kUserRelationBoth]==NSOrderedSame) {
        [deleteButton setTitle:@"删除" forState:UIControlStateNormal];
    }
    else {
        [deleteButton setTitle:@"恢复" forState:UIControlStateNormal];
    }
}

#pragma mark - operation methods

- (void) actionSheet:(UIActionSheet*)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if ( actionSheet.tag == kActionSheetFollow ) {
        if ( buttonIndex == 0 ) {
            [self destroyFriendship];
        }
    }
    else if ( actionSheet.tag == kActionSheetRequestCard ) {
        if ( buttonIndex == 0 ) {
            [self askCard];
        }
    }
}


//删除或者恢复联系人
- (void) friendship
{
    if ( owner ) return;
    
    if ( [user.relation compare:kUserRelationFollowing]==NSOrderedSame || [user.relation compare:kUserRelationBoth]==NSOrderedSame) {
        NSString* message = [NSString stringWithFormat:@"您是否确认删除联系人‘%@’?", user.screenName];
        UIActionSheet* as = [[UIActionSheet alloc] initWithTitle:message 
                                                        delegate:self 
                                               cancelButtonTitle:@"取消" 
                                          destructiveButtonTitle:@"确定" 
                                               otherButtonTitles:nil];
        as.tag = kActionSheetFollow;
        [as showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
        [as release];
    }
    else {
        [self createFriendship];
        //[self showFollowButton:cell];
    }
}


- (void) createFriendship
{
    //关注
    [UserService createFriendship:user];
    [[[GuaziAppDelegate getAppDelegate] friendsViewController] refreshCreateFriendship:user];
    [self setDeleteButtonTitle];
}


- (void) destroyFriendship
{
    //取消关注
    [UserService destroyFriendship:user];
    [[[GuaziAppDelegate getAppDelegate] friendsViewController] refreshDestroyFriendship:user.userId];
    [self setDeleteButtonTitle];
}


//名片
- (void) friendCards
{
    NSArray* cards = user.cards;
    if ( [cards count] == 0 ) {
        //索要名片
        UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:[NSString stringWithFormat:@"您还没有%@的名片。索要名片后，系统会自动发送一封私信给您的朋友。您的朋友收到私信后将发送名片给您。是否索要名片？", user.remarkName] 
                                                           delegate:self 
                                                  cancelButtonTitle:@"放弃" 
                                             destructiveButtonTitle:@"确定" 
                                                  otherButtonTitles:nil];
        sheet.tag = kActionSheetRequestCard;
        [sheet showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
        [sheet release];
    }
    else {
        //名片列表
        Card* card = [cards objectAtIndex:0];
        CardDetailViewController* controller = [[CardDetailViewController alloc] initWithCard:card];
        [self.navigationController pushViewController:controller animated:YES];
        [controller release];
    }
}


- (void) askCard
{
    if ( twitterClient != nil ) return;
    twitterClient = [[TwitterClient alloc] initWithTarget:self action:@selector(didAskCard:obj:)];
    [twitterClient askCard:user.userId];
}


- (void) didAskCard:(id)sender obj:(NSObject*)obj
{
    twitterClient = nil;
    
    TwitterClient* client = (TwitterClient*) sender;
    if ( [client hasError] ) {
        [client alert];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" 
                                                        message:@"已经向您的朋友发送了索要名片私信！" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"确定" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}


//设置分组
- (void) setUserGroup
{
	ContactGroupViewController* controller = [[ContactGroupViewController alloc] initWithStyle:UITableViewStylePlain user:user];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


//发私信
- (void)postDirectMessage
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView editDirectMessage:user.screenName];
}


//发动态
- (void) postTweet
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView reply:user.screenName];
}


//发短信
- (void) sendMessage
{
	NSArray* array = [NSArray arrayWithObject:user.phone];
    [self send:array body:@""];
	//MessagePicker* picker = [[MessagePicker alloc] initWithController:self recienpts:array body:@""];
	//[picker send];
	//[picker release];
}

//打电话
- (void) callPhone
{
	NSString* url = [NSString stringWithFormat:@"tel://%@", user.phone];
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

//看用户的动态
- (void) friendTimeline
{
    UserTimelineController* controller = [[UserTimelineController alloc] initWithUser:user];
    //[controller loadUserTimeline:user.userId];
    [self.navigationController pushViewController:controller animated:true];
    [controller release];
}

//看用户好友
- (void) friendList
{
    FriendListViewController *controller = [[FriendListViewController alloc] initWithUser:user isFollowers:NO];
    [self.navigationController pushViewController:controller animated:true];
    [controller release];
}

#pragma mark - SMS operations

-(void) send:(NSArray*)recipients body:(NSString*)body
{
	Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
	if (messageClass != nil) {
		// Check whether the current device is configured for sending SMS messages
		if ([messageClass canSendText]) {
			[self displaySMSComposerSheet:recipients body:body];
		}
		else {
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设备没有短信功能" 
															message:@"您的设备不能发送短信" 
														   delegate:nil 
												  cancelButtonTitle:@"确定" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
	}
	else {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"iOS版本过低" 
														message:@"iOS版本过低,iOS4.0以上才支持程序内发送短信" 
													   delegate:nil 
											  cancelButtonTitle:@"确定" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
}


-(void)displaySMSComposerSheet:(NSArray*)recipients body:(NSString*)body
{
	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
	picker.messageComposeDelegate = self;
	picker.recipients = recipients;
	picker.body = body;
    picker.title = @"发送短信";
    
	[self.navigationController presentModalViewController:picker animated:YES];
	[picker release];
}


- (void)messageComposeViewController:(MFMessageComposeViewController *)messageComposeViewController
				 didFinishWithResult:(MessageComposeResult)result {
	switch (result)
	{
		case MessageComposeResultCancelled:
			NSLog(@"Result: SMS sending canceled");
			break;
		case MessageComposeResultSent:
			NSLog(@"Result: SMS sent");
			break;
		case MessageComposeResultFailed:
			NSLog(@"Result: sms fail");
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"短信发送失败" 
															message:@"短信发送失败" 
														   delegate:nil 
												  cancelButtonTitle:@"确定" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
			break;
		default:
			NSLog(@"Result: SMS not sent");
			break;
	}
    
    [self.navigationController dismissModalViewControllerAnimated:YES];
}


@end
